package top.bulk.encrypt.util;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.CryptoException;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.extra.spring.SpringUtil;
import top.bulk.encrypt.strategy.CryptoProperties;

/**
 * @author 散装java
 * @date 2024-07-26
 */
public class CryptoUtils {

    /**
     * 获取aes 加密算法
     */
    public static AES aes(String[] arguments) {
        String aesKey;
        if (ArrayUtil.isEmpty(arguments)) {
            CryptoProperties cryptoProperties = SpringUtil.getBean(CryptoProperties.class);
            aesKey = cryptoProperties.getAesKey();
        } else {
            aesKey = arguments[0];
        }

        return SecureUtil.aes(aesKey.getBytes());
    }

    /**
     * 获取RSA加密算法
     */
    public static RSA rsa(String[] arguments) {
        String privateKey;
        String publicKey;
        if (ArrayUtil.isEmpty(arguments) || arguments.length != 2) {
            CryptoProperties cryptoProperties = SpringUtil.getBean(CryptoProperties.class);
            privateKey = cryptoProperties.getRsaPrivateKey();
            publicKey = cryptoProperties.getRsaPublicKey();
        } else {
            privateKey = arguments[0];
            publicKey = arguments[1];
        }

        return SecureUtil.rsa(privateKey, publicKey);
    }

    public static String requireNonBlank(String content, String message) {
        if (StrUtil.isBlank(content)) {
            throw new CryptoException(message);
        }
        return content;
    }
}
